package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.mapper.vo.PicUploadResult;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class VideoService {
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference(version = "1.0.0",check = false)
    private VideoApi videoApi;
    @Autowired
    UserInfoService userInfoService;
    @Reference(version = "1.0.0",check = false)
    QuanZiApi quanZiApi;
    @Autowired
    QuanZiService quanZiService;

    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        try {
            Video video = new Video();
            User user = UserThreadLocal.getuser();
            PicUploadResult upload = picUploadService.upload(picFile);
            video.setSeeType(1); //默认公开
            video.setPicUrl(upload.getName());
            video.setUserId(user.getId());
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true),
                    null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl()+storePath.getFullPath());
            return StringUtils.isNotEmpty(videoApi.saveVideo(video));
        } catch (IOException e) {
            log.error("发布小视频失败！file = " + picFile.getOriginalFilename() , e);
        }

        return false;
    }

    public PageResult queryVideoList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.getuser();
        PageResult pageResult = new PageResult();
        PageInfo<Video> videoPageInfo = videoApi.queryVideoList(user.getId(), page, pageSize);
        List<Video> records = videoPageInfo.getRecords();
        if(CollUtil.isEmpty(records))
            return pageResult;
        List<Object> userId = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userId);
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo = new VideoVo();

            videoVo.setUserId(record.getUserId());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setSignature("我就是我~"); //TODO 签名

            videoVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(videoVo.getId()))); //TODO 评论数
            videoVo.setHasFocus(videoApi.isFollowUser(user.getId(),videoVo.getUserId()) ? 1:0); //TODO 是否关注
            videoVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(),videoVo.getId()) ? 1 : 0); //TODO 是否点赞（1是，0否）
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));//TODO 点赞数

            //填充用户信息
            for (UserInfo userInfo : userInfos) {
                if (ObjectUtil.equals(videoVo.getUserId(), userInfo.getUserId())) {
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            }

            videoVoList.add(videoVo);
        }

        pageResult.setItems(videoVoList);
        return pageResult;


        }

    public Long likeComment(String videoId) {
        User user = UserThreadLocal.getuser();

        Boolean aBoolean = quanZiApi.likeComment(user.getId(), videoId);
        if(aBoolean) {
            Long aLong = quanZiApi.queryLikeCount(videoId);
            return aLong;
        }
        return null;

    }

    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.getuser();
        Boolean aBoolean = quanZiApi.disLikeComment(user.getId(), videoId);
        if(aBoolean) {
            Long aLong = quanZiApi.queryLikeCount(videoId);
            return aLong;
        }
        return null;
    }

    public Boolean saveComment(String videoId, String content) {
        User user = UserThreadLocal.getuser();
        Boolean aBoolean = quanZiApi.saveComment(user.getId(), videoId, content);
        return aBoolean;
    }

    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
      return quanZiService.queryCommentList(videoId,page,pageSize);
    }

    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.getuser();
        return videoApi.disFollowUser(user.getId(), userId);
    }

    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.getuser();
        return videoApi.followUser(user.getId(), userId);
    }
}

